//
//  ComposeViewController.swift
//  SinaWeibo
//
//  Created by 张洪毓 on 15/11/19.
//  Copyright © 2015年 张洪毓. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD
class ComposeViewController: UIViewController {
    
    private lazy var keyBoardView: EmoticonKeyBoardView = EmoticonKeyBoardView {[weak self] (emo) -> () in
        self?.textView.insertAttrText(emo)
    }
    
    @objc private func selectPiture() {
        selectorVC.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(224+80+40)
        }
    }
    
    @objc private func selectEmoticon() {
        //取消第一响应者
        textView.resignFirstResponder()
        //设置输入视图
        textView.inputView = (textView.inputView == nil ? keyBoardView : nil)
        //成为第一响应者
        textView.becomeFirstResponder()
    }
    
    //监听方法
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func send() {

        guard let token = UserAccountViewModel().token else {
            SVProgressHUD.showErrorWithStatus("笨蛋，你还未登录呢")
            return
        }
        
        let parameters = ["access_token": token, "status": textView.fullText()]
        if selectorVC.imageList.count >= 1 {
            let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            let imageData = UIImagePNGRepresentation(selectorVC.imageList[0])
            
            NetworkTools.sharedTools.uploadImage(urlString, parameters: parameters, imageData: imageData!, finished: { (result, error) -> () in
                if error != nil {
                    SVProgressHUD.showErrorWithStatus("笨蛋2，你还未登录呢")
                    return
                }
                SVProgressHUD.showSuccessWithStatus("发布微博成功")
                self.dismissViewControllerAnimated(true, completion: nil)
            })
        }else {
            let urlString = "2/statuses/update.json"
            NetworkTools.sharedTools.requestJsonDict(.POST, urlString: urlString, parameters: parameters, finished: { (result, error) -> () in
                if error != nil {
                    SVProgressHUD.showErrorWithStatus("笨蛋2，你还未登录呢")
                    return
                }
                SVProgressHUD.showSuccessWithStatus("发布微博成功")
                self.dismissViewControllerAnimated(true, completion: nil)
                print(result)
            })
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        setupUI()
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        textView.becomeFirstResponder()
    }
    
    private func setupUI() {
        //设置导航条
        setNaviBar()
        //设置输入文本
        setupTextView()
        //设置底部工具条
        setupToolBar()
        //注册通知
        registerNotification()
        //添加图片选择控制器视图
        setSelectorView()
    }
    
    private func setSelectorView() {
        addChildViewController(selectorVC)
        view.addSubview(selectorVC.view)
        view.bringSubviewToFront(toolBar)
        selectorVC.view.snp_makeConstraints { (make) -> Void in
            make.left.bottom.right.equalTo(view)
            make.height.equalTo(0)
        }
    }
    
    private func registerNotification() {
        //添加通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    deinit {
        //移除通知
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //通知的响应方法
    @objc private func keyboardWillChange(noti: NSNotification){
        //        print(noti)
                /*
                NSConcreteNotification 0x7f88da4c2f50 {
    name     = UIKeyboardWillChangeFrameNotification;
    userInfo = {
                UIKeyboardAnimationCurveUserInfoKey = 7;
                UIKeyboardAnimationDurationUserInfoKey = 0;
                UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 216}}";
                UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 775}";
                UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 775}";
                UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 216}}";
                UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 667}, {375, 216}}";
                UIKeyboardIsLocalUserInfoKey = 1;
                }}
                */
        //获取动画事件
        let duration = noti.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
        let rect = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        //动画曲线值
        let curve = noti.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! Int
        //修改toolBar约束
        //获取键盘高度
        let offset = -(kScreenSize.height - rect.origin.y)
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(offset)
        }
        
        UIView.animateWithDuration(duration) { () -> Void in
            //设置动画曲线值，如果设置了这个值为7，那么动画持续时间失效
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
            //强制刷新
            self.view.layoutIfNeeded()
        }
    }
    
    //懒加载控件
    private lazy var textView: EmoticonTextView = {
        let tv = EmoticonTextView()
        //tv.text = "分享新鲜事..."
        //设置键盘消失模式
        tv.delegate = self
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        //设置弹簧效果开启
        tv.alwaysBounceVertical = true
        tv.font = UIFont.systemFontOfSize(18)
        tv.textColor = UIColor.darkGrayColor()
        return tv
    }()
    
    //懒加载占位文本
    private lazy var placeHolderLabel = UILabel(title: "分享新鲜事...", size: 18, color: UIColor.lightGrayColor())
    private lazy var toolBar = UIToolbar()
    private lazy var selectorVC: PictureSelectorViewController = PictureSelectorViewController()
    
}

extension ComposeViewController: UITextViewDelegate {
    func textViewDidChangeSelection(textView: UITextView) {
        //设置占位文本隐藏
        placeHolderLabel.hidden = textView.hasText()
        //设置发布按钮的交互
        self.navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}

extension ComposeViewController {
    
    private func setNaviBar() {

        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: "send")
        self.navigationItem.rightBarButtonItem?.enabled = false
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
        
        navigationItem.titleView = titleView
//        navigationItem.prompt = "发微博"
//        navigationItem.title = UserAccountViewModel().userName ?? ""
        
        //添加导航栏发布信息的视图
        let titleLabel = UILabel(title: "发微博", size: 16, color: UIColor.darkGrayColor())
        let nameLabel = UILabel(title: UserAccountViewModel().userName ?? "", size: 14, color: UIColor.lightGrayColor())
        //添加子视图
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        //设置约束
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(titleView.snp_top)
            make.centerX.equalTo(titleView.snp_centerX)
        }
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(titleView.snp_bottom)
            make.centerX.equalTo(titleView.snp_centerX)
        }
    }
    
    private func setupTextView() {
        view.addSubview(textView)
        //        textView.backgroundColor = UIColor.randomColor()
        
        //设置约束
        textView.snp_makeConstraints { (make) -> Void in
            make.top.left.right.equalTo(self.view)
            make.height.equalTo(self.view.bounds.height / 3)
        }
        
        //添加占位文本
        textView.addSubview(placeHolderLabel)
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_top).offset(5)
        }
    }
    
    private func setupToolBar() {
        //添加控件
        view.addSubview(toolBar)
        //添加约束
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.bottom.right.equalTo(view)
            make.height.equalTo(40)
        }
        //设置toolBar的按钮，以及点击事件
        var items = [UIBarButtonItem]()
        //添加UIBarButtonItem
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName":"selectPiture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background","actionName":"selectEmoticon"],
            ["imageName": "compose_add_background"]]
        for dict in itemSettings {
            //            let btn = UIButton()
            //            let imageName = dict["imageName"]!
            //            btn.setImage(UIImage(named: imageName), forState: .Normal)
            //            btn.setImage(UIImage(named: imageName + "_highlighted"), forState: .Highlighted)
            //            let item = UIBarButtonItem(customView: btn)
            //            btn.sizeToFit()
            let item = UIBarButtonItem(imageName: dict["imageName"]!, target: self, actionName: dict["actionName"])
            items.append(item)
            //实例化弹簧
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(space)
        }
        //删除最后一个弹簧
        items.removeLast()
        toolBar.items = items
    }    
}






